﻿import { EnumDetectStatus } from "@/enums/business/detect.enum";
import { useSignalRStore } from "@/store/modules/signalr.store";
import { SignalrToken } from "@/enums/business/signalrToken.enum";
import DetectApi from "@/api/business/detect.api";
import { format } from "date-fns";

// 检测相关
export const useDetectStore = defineStore("detect", () => {
  // 当前检测状态
  const detectStatus = ref(EnumDetectStatus.NotReady);
  // 是否正在检测中
  const isDetecting = ref(false);
  watch(
    detectStatus,
    (newVal) => {
      isDetecting.value = newVal !== EnumDetectStatus.NotReady && newVal !== EnumDetectStatus.Ready;
    },
    { immediate: true }
  );

  const signalrStore = useSignalRStore();

  // region 更新检定状态

  onMounted(() => {
    DetectApi.getDetectStatus().then((res) => {
      detectStatus.value = res;
    });
  });

  signalrStore.subscribe(SignalrToken.DetectStatus, (status: EnumDetectStatus) => {
    detectStatus.value = status;
  });

  // endregion

  // region 检定过程消息

  // 检定消息
  const detectMessages = useStorage<{ time: string; message: string; type: string }[]>(
    "detectMessages",
    [] as { time: string; message: string; type: string }[]
  );

  /**
   * 添加检定消息
   * @param message 消息
   * @param type 类型
   * @param isConfirmBox 是否为确认框
   */
  function addDetectMessage(type: string, message: string, isConfirmBox: boolean) {
    if (detectMessages.value.length > 100) detectMessages.value.pop();
    const item = {
      time: format(new Date(), "HH:mm:ss.SSS"),
      message,
      type,
    };
    if (isConfirmBox) {
      const message = item.message.replace(/\n/g, "<br>");
      ElMessageBox.alert(message, "⚠️ 提示", {
        confirmButtonText: "确定",
        dangerouslyUseHTMLString: true,
        type: item.type,
      });
    } else {
      ElNotification({
        title: item.time,
        message: item.message,
        type: item.type,
        position: "bottom-right",
      });
    }
    detectMessages.value.unshift(item);
  }

  /**
   * 清空检定消息
   */
  function clearDetectMessages() {
    detectMessages.value.length = 0;
  }

  onMounted(() => {
    signalrStore.subscribe(
      SignalrToken.DetectNotification,
      (type: string, message: string, isConfirmBox: boolean) => {
        addDetectMessage(type, message, isConfirmBox);
      }
    );
  });

  // endregion

  return {
    detectStatus,
    isDetecting,
    detectMessages,
    addDetectMessage,
    clearDetectMessages,
  };
});
